from django.conf import settings
from rest_framework import serializers

from celery_tasks.email.tasks import send_email
from goods.models import SKU
from users.models import User
from django_redis import get_redis_connection
import re
from rest_framework_jwt.settings import api_settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS


class UserSerializer(serializers.ModelSerializer):
    # 显示指明字段
    password2 = serializers.CharField(max_length=20, min_length=8, write_only=True)
    sms_code = serializers.CharField(max_length=6, min_length=6, write_only=True)
    allow = serializers.CharField(write_only=True)
    user_id = serializers.IntegerField(read_only=True)
    token = serializers.CharField(read_only=True)  # 额外添加token

    class Meta:
        model = User
        fields = ('user_id', 'username', 'mobile', 'email', 'password', 'password2', 'sms_code', 'allow', 'token')
        extra_kwargs = {
            'password': {
                'write_only': True,
                'max_length': 20,
                'min_length': 8,
                'error_messages': {
                    'max_length': '密码过长'
                }
            },
            'username': {
                'max_length': 20,
                'min_length': 5,
                'error_messages': {
                    'max_length': '名字过长',
                    'min_length': '名字过短'
                }
            },
        }

    # 手机号验证
    def validate_mobile(self, value):

        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机格式不正确')

        return value

    # 验证选中协议状态
    def validate_allow(self, value):

        if value != 'true':
            raise serializers.ValidationError('协议未选中')

        return value

    def validate(self, attrs):

        #  判断username是否是手机号
        if re.match(r'^1[3-9]\d{9}$', attrs['username']):
            if attrs['username'] != attrs['mobile']:
                raise serializers.ValidationError('用户名和手机号不一致')

        # 密码比对
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('密码不一致')

        # 短信验证码判断
        # 建立缓存redis连接
        conn = get_redis_connection('verify_codes')

        # 取出真实验证码   bytes
        real_sms = conn.get('sms_%s' % attrs['mobile'])

        # 判断是否能取出值
        if not real_sms:
            raise serializers.ValidationError('短信验证码已过期')

        # 验证码比对
        if attrs['sms_code'] != real_sms.decode():
            raise serializers.ValidationError('短信验证码不一致')

        return attrs

    def create(self, validated_data):
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        # 手动加密
        user = User.objects.create(username=validated_data['username'], mobile=validated_data['mobile'],
                                   password=validated_data['password'])
        user.set_password(validated_data['password'])
        user.save()

        # 创建完成用户对象之前生成token值
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 生成ｔｏｋｅｎ并保存
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        user.user_id = user.id

        return user


class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'id', 'mobile', 'email', 'email_active')


class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ("id", "email")

    # 重写update方法
    def update(self, instance, validated_data):
        # 加密用户信息
        tjs = TJS(settings.SECRET_KEY, 300)
        token = tjs.dumps({"id": instance.id}).decode()
        # 构建验证连接
        verify_html = '<a href="http://www.meiduo.site:8080/success_verify_email.static_html?token={}">美多商城验证</a>'.format(
            token)
        # 发送邮件
        send_email(validated_data["email"], verify_html)
        instance.email = validated_data["email"]
        instance.save()

        return instance


class VerifyEmailSerializer(serializers.Serializer):
    token = serializers.CharField(write_only=True)

    def validate(self, attrs):
        # 取出token，　并解密
        tjs = TJS(settings.SECRET_KEY, 300)
        try:
            token = tjs.loads(attrs["token"])
        except:
            raise serializers.ValidationError({"errors": "无效的token"})

        # 取出token中user对象
        user = User.objects.get(id=token["id"])

        # user对象
        attrs["user"] = user

        return attrs

    def create(self, validated_data):
        user = validated_data["user"]
        user.email_active = True
        user.save()
        return user


class AddUserBrowsingHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label="商品ｓｋｕ编号", min_value=1)  # 注意 ming_value和min_length的区别

    def validate_sku_id(self, value):
        # 通过sku_id查找sku对象
        try:
            sku = SKU.objects.get(id=value)
        except:
            raise serializers.ValidationError("商品不存在")

        return value

    def create(self, validated_data):
        """使用ｒｅｄｉｓ保存用户浏览记录"""
        user_id = self.context["request"].user.id
        sku_id = validated_data["sku_id"]

        # 连接ｒｅｄｉｓ数据库
        conn = get_redis_connection("history")

        # 移除已经存在的浏览记录
        conn.lrem("history_%s" % user_id, 0, sku_id)

        # 添加新的浏览记录
        conn.lpush("history_%s" % user_id, sku_id)

        # 只保存最多５条记录
        conn.ltrim("history_%s" % user_id, 0, 4)

        return validated_data
